package com.achievement.service.impl;

import com.achievement.domain.bo.HonorApplyBookBO;
import com.achievement.domain.bo.HonorApplyInfoBO;
import com.achievement.domain.dto.honor.HonorApplyBookDTO;
import com.achievement.domain.dto.honor.HonorApplyBookMemberDTO;
import com.achievement.domain.entity.*;
import com.achievement.domain.param.honor.HonorApplyBookParam;
import com.achievement.domain.param.honor.HonorApplyInfoParam;
import com.achievement.domain.vo.honor.*;
import com.achievement.mapper.*;
import com.achievement.mappings.*;
import com.achievement.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.api.ApprovalApi;
import com.common.core.domain.AjaxResult;
import com.common.utils.DateUtils;
import com.common.utils.QueryWrapperUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.bean.BizProcessMessages;
import com.common.utils.bean.ReflectionUtils;
import com.flowable.domain.vo.task.BpmTaskApproveReqVO;
import com.flowable.service.IFlowTaskService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class HonorApplyBookServiceImpl extends ServiceImpl<HonorApplyBookMapper, HonorApplyBookEntity> implements IHonorApplyBookService {
    @Autowired
    private HonorApplyBookMapper honorApplyBookMapper;
    @Autowired
    private IHonorApplyBookMemberService honorApplyBookMemberService;
    @Autowired
    private HonorApplyBookMapping mapping;
    @Autowired
    private HonorMapping honorMapping;
    @Autowired
    private HonorMapper honorMapper;
    @Autowired
    private HonorApplyBookMemberMapper honorApplyBookMemberMapper;
    @Autowired
    private HonorApplyBookMemberMapping honorApplyBookMemberMapping;
    @Autowired
    private HonorAuthorMapping honorAuthorMapping;
    @Autowired
    private HonorAuthorMapper honorAuthorMapper;
    @Autowired
    private ExpertReviewMapping expertReviewMapping;
    @Autowired
    private ExpertReviewMapper expertReviewMapper;
    @Autowired
    private IExpertReviewService expertReviewService;
    @Autowired
    private IReviewResultService reviewResultService;

    @Autowired
    private IReviewStandardService reviewStandardService;
    @Autowired
    private IAchievementFileService fileService;
    //流程引擎
    @Autowired
    private IFlowTaskService flowTaskService;

    @Autowired
    private ApprovalApi approvalApi;
    private final static String module_name = "申报获奖";
    @Override
    public List<HonorApplyBookReviewVO> listByPage(HonorApplyBookParam param){

        HonorApplyBookBO honorApplyBookBO=mapping.param2Bo(param);
        if(StringUtils.isNotEmpty(param.getCheckstatus())&&!param.getCheckstatus().equals("[]")){
            List<String> checkstatusTypes=Arrays.stream(param.getCheckstatus().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setCheckstatusTypes(checkstatusTypes);
        }
        if(StringUtils.isNotEmpty(param.getUnitId())&&!param.getUnitId().equals("[]")){
            List<String> unitIds=Arrays.stream(param.getUnitId().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setUnitIds(unitIds);
        }
        if(StringUtils.isNotEmpty(param.getHonorState())&&!param.getHonorState().equals("[]")){
            List<String> honorStateIds=Arrays.stream(param.getHonorState().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setHonorStateIds(honorStateIds);
        }
        if(StringUtils.isNotEmpty(param.getSubjectId())&&!param.getSubjectId().equals("[]")){
            List<String> subjectIds=Arrays.stream(param.getSubjectId().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setSubjectIds(subjectIds);
        }
        //科研秘书，当前计划下的所属单位是自己管理单位的所有申报成果数据
        LambdaQueryWrapper<HonorApplyBookEntity> queryWrapper = new LambdaQueryWrapper();
        QueryWrapperUtils.getParams_NokyryWithAlias(queryWrapper, SecurityUtils.getLoginUser().getUser(),"b");
        return honorApplyBookMapper.listByPage(honorApplyBookBO,queryWrapper);
    }
    @Override
    public List<HashMap<String, Integer>> listStatistics(HonorApplyBookParam param){

        HonorApplyBookBO honorApplyBookBO=mapping.param2Bo(param);
        if(StringUtils.isNotEmpty(param.getCheckstatus())&&!param.getCheckstatus().equals("[]")){
            List<String> checkstatusTypes=Arrays.stream(param.getCheckstatus().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setCheckstatusTypes(checkstatusTypes);
        }
        if(StringUtils.isNotEmpty(param.getUnitId())&&!param.getUnitId().equals("[]")){
            List<String> unitIds=Arrays.stream(param.getUnitId().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setUnitIds(unitIds);
        }
        if(StringUtils.isNotEmpty(param.getHonorState())&&!param.getHonorState().equals("[]")){
            List<String> honorStateIds=Arrays.stream(param.getHonorState().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setHonorStateIds(honorStateIds);
        }
        if(StringUtils.isNotEmpty(param.getSubjectId())&&!param.getSubjectId().equals("[]")){
            List<String> subjectIds=Arrays.stream(param.getSubjectId().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setSubjectIds(subjectIds);
        }
        //科研秘书，当前计划下的所属单位是自己管理单位的所有申报成果数据
        LambdaQueryWrapper<HonorApplyBookEntity> queryWrapper = new LambdaQueryWrapper();
        QueryWrapperUtils.getParams_NokyryWithAlias(queryWrapper, SecurityUtils.getLoginUser().getUser(),"b");
        return honorApplyBookMapper.listStatistics(honorApplyBookBO,queryWrapper);
    }
    public List<HonorApplyBookReviewVO> expertReviewBookListByReviewPlan(String applyInfoId, String reviewerId){
        HonorApplyBookBO honorApplyBookBO=new HonorApplyBookBO();
        honorApplyBookBO.setApplyInfoId(applyInfoId);
        honorApplyBookBO.setReviewerId(reviewerId);
        //科研秘书，当前计划下的所属单位是自己管理单位的所有申报成果数据
        LambdaQueryWrapper<HonorApplyBookEntity> queryWrapper = new LambdaQueryWrapper();
        QueryWrapperUtils.getParams_NokyryWithAlias(queryWrapper, SecurityUtils.getLoginUser().getUser(),"b");
        List<HonorApplyBookReviewVO> vos=honorApplyBookMapper.expertReviewBookListByReviewPlan(honorApplyBookBO,queryWrapper);
        //遍历每个专家评审数据
        if(ObjectUtils.isNotEmpty(vos)){
            List<String> objectIds=vos.stream().map(HonorApplyBookReviewVO::getId).collect(Collectors.toList());
            List<ExpertReviewEntity> expertReviews=expertReviewMapper.expertReviewMarkListByReviewerIdReviewObjectIds(reviewerId,objectIds);
            for(HonorApplyBookReviewVO vo:vos){
                ExpertReviewEntity mo=expertReviews.stream().filter(t->t.getReviewObjectId().equals(vo.getId())).findFirst().orElse(null);
                if(ObjectUtils.isNotEmpty(mo)&&mo.getReviewStatus().equals("submit")){
                    vo.setReviewMark(mo.getReviewMark());
                    vo.setReviewInfo(mo.getReviewInfo());
                    vo.setReviewResult(mo.getReviewResult());
                }
            }
        }
        return vos;
    }
    @Override
    public List<HonorApplyBookExcelVO> lisExcelByPage(HonorApplyBookParam param){

        HonorApplyBookBO honorApplyBookBO=mapping.param2Bo(param);
        if(StringUtils.isNotEmpty(param.getCheckstatus())&&!param.getCheckstatus().equals("[]")){
            List<String> checkstatusTypes=Arrays.stream(param.getCheckstatus().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setCheckstatusTypes(checkstatusTypes);
        }
        if(StringUtils.isNotEmpty(param.getUnitId())&&!param.getUnitId().equals("[]")){
            List<String> unitIds=Arrays.stream(param.getUnitId().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setUnitIds(unitIds);
        }
        if(StringUtils.isNotEmpty(param.getHonorState())&&!param.getHonorState().equals("[]")){
            List<String> honorStateIds=Arrays.stream(param.getHonorState().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setHonorStateIds(honorStateIds);
        }
        if(StringUtils.isNotEmpty(param.getSubjectId())&&!param.getSubjectId().equals("[]")){
            List<String> subjectIds=Arrays.stream(param.getSubjectId().split(",")).filter(id -> !id.trim().isEmpty()).collect(Collectors.toList());
            honorApplyBookBO.setSubjectIds(subjectIds);
        }
        //科研秘书，当前计划下的所属单位是自己管理单位的所有申报成果数据
        LambdaQueryWrapper<HonorApplyBookEntity> queryWrapper = new LambdaQueryWrapper();
        QueryWrapperUtils.getParams_NokyryWithAlias(queryWrapper, SecurityUtils.getLoginUser().getUser(),"b");
        return honorApplyBookMapper.lisExcelByPage(honorApplyBookBO,queryWrapper);
    }

    @Override
    public List<HonorApplyBookEntity> getListByConditions(HonorApplyBookDTO patentDTO) {
        QueryWrapper<HonorApplyBookEntity> queryWrapper = new QueryWrapper();
        List<HonorApplyBookEntity> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public HonorApplyBookVO getInfoById(String id) {
        HonorApplyBookEntity entity = this.getById(id);
        HonorApplyBookVO honorApplyBookVO=mapping.entity2Vo(entity);
        List<HonorApplyBookMemberVO> honorApplyBookMemberVOs=honorApplyBookMemberService.honorApplyBookMemberByApplyBookId(id);
        honorApplyBookVO.setHonorApplyBookMemberVOs(honorApplyBookMemberVOs);
        if (com.common.utils.StringUtils.hasText(entity.getFileIds())) {
            String[] fileIdArr = entity.getFileIds().split(",");
            List<Map<String,String>> fileInfo = fileService.getFileInfoByFileIds(fileIdArr);
            honorApplyBookVO.setFileList(fileInfo);
        }
        return honorApplyBookVO;
    }

    @Override
    public boolean add(HonorApplyBookDTO dto) {
        HonorApplyBookEntity entity = mapping.dto2Entity(dto);
        return this.save(entity);
    }


    @Override
    public boolean update(HonorApplyBookDTO dto) {
        HonorApplyBookEntity entity = mapping.dto2Entity(dto);
        return this.updateById(entity);
    }

    @Override
    public List<AchievementExpertVO> allExpertList(){
        return honorApplyBookMapper.allExpertList();
    }
    @Override
    public AchievementExpertVO ExpertById(String id){
        return honorApplyBookMapper.ExpertById(id);
    }
    @Override
    public boolean batchRemove(List<String> ids) {
        boolean returnResult=false;
        returnResult=this.removeByIds(ids);
        if(returnResult){
            for (String id:ids
                 ) {
                //遍历删除作者信息
                honorApplyBookMemberService.deleteHonorApplyBookMemberListByApplyBookId(id);
            }

        }
        return returnResult;
    }
    @Override
    public AjaxResult addHonorApplyBookAndHonorApplyBookMember(HonorApplyBookDTO dto) {
        Integer submitType = dto.getSubmitType();
        boolean returnResult=false;
        HonorApplyBookEntity entity = mapping.dto2Entity(dto);
        if(!dto.getHonorApplyBookMemberDTOs().isEmpty()){
            List<HonorApplyBookMemberDTO> memberDTOS=dto.getHonorApplyBookMemberDTOs();
            String authorPIds= memberDTOS.stream().map(a -> a.getPersonId()).collect(Collectors.joining(","));
            String authorNames= memberDTOS.stream().map(a -> a.getAuthorName()).collect(Collectors.joining(","));
            entity.setAuthorpids(authorPIds);
            entity.setAuthornames(authorNames);
        }
        entity.setHonorState("0");
        switch (submitType) {
            case 2: // 保存并通过
                entity.setProcessInstanceId("0");
                entity.setCheckdate(DateUtils.parseDate(DateUtils.getTime()));
                entity.setChecker(SecurityUtils.getNickName());
                entity.setCheckstatus(String.valueOf(submitType));
                break;
            case 1: // 提交
                returnResult=this.save(entity);
                if (!returnResult) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                if(returnResult&&!dto.getHonorApplyBookMemberDTOs().isEmpty()){
                    honorApplyBookMemberService.bitchAdd(dto.getHonorApplyBookMemberDTOs(),entity.getId());
                }
                String processInstanceId = null;
                try {
                    //发起流程 业务状态由流程引擎更新
                    processInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS);
                }
                return com.common.utils.StringUtils.isEmpty(processInstanceId)
                        ? AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
            default: // 处理 -1（暂存）及其他情况
                entity.setCheckstatus(String.valueOf(submitType));
                break;
        }

        returnResult=this.save(entity);
        if(returnResult&&!dto.getHonorApplyBookMemberDTOs().isEmpty()){
            honorApplyBookMemberService.bitchAdd(dto.getHonorApplyBookMemberDTOs(),entity.getId());
        }
        return returnResult
                ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                : AjaxResult.error(BizProcessMessages.SAVE_FAIL);

    }
    @Override
    public AjaxResult updateHonorApplyBookAndHonorApplyBookMember(HonorApplyBookDTO dto){
        Integer submitType = dto.getSubmitType();
        boolean returnResult=false;
        HonorApplyBookEntity entity = mapping.dto2Entity(dto);
        if(!dto.getHonorApplyBookMemberDTOs().isEmpty()){
            List<HonorApplyBookMemberDTO> memberDTOS=dto.getHonorApplyBookMemberDTOs();
            String authorPIds= memberDTOS.stream().map(a -> a.getPersonId()).collect(Collectors.joining(","));
            String authorNames= memberDTOS.stream().map(a -> a.getAuthorName()).collect(Collectors.joining(","));
            entity.setAuthorpids(authorPIds);
            entity.setAuthornames(authorNames);
        }else{
            entity.setAuthorpids("");
            entity.setAuthornames("");
        }
        switch (submitType) {
            case 2: // 保存并通过
                // 当前用户是否是审批人
                boolean isAuditor = dto.getIsAuditor();
                // 审批人直接审核（仅适用于提交类型2且为当前审核人的情况）
                if (isAuditor) {
                    returnResult=this.updateById(entity);
                    if(returnResult){
                        honorApplyBookMemberService.deleteHonorApplyBookMemberListByApplyBookId(dto.getId());
                        if(!dto.getHonorApplyBookMemberDTOs().isEmpty()){
                            honorApplyBookMemberService.bitchAdd(dto.getHonorApplyBookMemberDTOs(),entity.getId());
                        }
                        BpmTaskApproveReqVO bta = new BpmTaskApproveReqVO();
                        bta.setId(dto.getTaskId());
                        bta.setReason(SecurityUtils.getNickName() + "保存并通过");
                        try {
                            flowTaskService.approveTask(SecurityUtils.getUserId(), bta);
                        } catch (Exception e) {
                            return AjaxResult.error(BizProcessMessages.SAVE_SUCCESS_APPROVE_FAIL, e.getMessage());
                        }
                        return AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
                    }
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                //处理非当前审批人保存并通过
                if (!dto.getCheckstatus().equals("2")){
                    entity.setProcessInstanceId("0");
                }
                entity.setCheckdate(DateUtils.parseDate(DateUtils.getTime()));
                entity.setChecker(SecurityUtils.getNickName());
                //只有管理员才会有非当前审核人的情况下有 "保存并提交"按钮,审核完后的结果只能是审核通过
                entity.setCheckstatus(String.valueOf(submitType));
                break;
            case 1:
                returnResult=this.updateById(entity);
                //暂存转提交
                if (!returnResult) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                honorApplyBookMemberService.deleteHonorApplyBookMemberListByApplyBookId(dto.getId());
                if(!dto.getHonorApplyBookMemberDTOs().isEmpty()){
                    honorApplyBookMemberService.bitchAdd(dto.getHonorApplyBookMemberDTOs(),entity.getId());
                }
                String returnProcessInstanceId = null;
                try {
                    returnProcessInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    return AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS, e.getMessage());
                }

                return com.common.utils.StringUtils.isEmpty(returnProcessInstanceId)
                        ? AjaxResult.warn(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
            case -1: // 暂存
                returnResult=this.updateById(entity);
                if (returnResult) {
                    honorApplyBookMemberService.deleteHonorApplyBookMemberListByApplyBookId(dto.getId());
                    if(!dto.getHonorApplyBookMemberDTOs().isEmpty()){
                        honorApplyBookMemberService.bitchAdd(dto.getHonorApplyBookMemberDTOs(),entity.getId());
                    }
                }
                return returnResult
                        ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                        : AjaxResult.error(BizProcessMessages.SAVE_FAIL);
            default:
                break;
        }
        returnResult=this.updateById(entity);
        if(returnResult){
            honorApplyBookMemberService.deleteHonorApplyBookMemberListByApplyBookId(dto.getId());
            if(!dto.getHonorApplyBookMemberDTOs().isEmpty()){
                honorApplyBookMemberService.bitchAdd(dto.getHonorApplyBookMemberDTOs(),entity.getId());
            }
        }
        return returnResult
                ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                : AjaxResult.error(BizProcessMessages.SAVE_FAIL);
    }

    /**
     * 管理员查看专家评审意见汇总
     * @param id
     * @return
     */
    @Override
    public HonorApplyBookExpertReviewResultVO honorApplyBookExpertReviewDetailById(@Param(value = "id") String id){
        //获取获奖评审-查看成果列表-意见汇总-意见详情返回基本信息
        HonorApplyBookExpertReviewResultVO honorApplyBookExpertReviewResultVO=honorApplyBookMapper.honorApplyBookExpertReviewDetailById(id);
        if(ObjectUtils.isNotEmpty(honorApplyBookExpertReviewResultVO)){
            //获取该成果下所有分配的专家信息
            LambdaQueryWrapper<ExpertReviewEntity> expertReviewQueryWrapper = new LambdaQueryWrapper();
            expertReviewQueryWrapper.eq(ExpertReviewEntity::getReviewObjectId,honorApplyBookExpertReviewResultVO.getId());
            List<ExpertReviewVO> expertReviewVoList = expertReviewService.selectByLambdaQueryWrapper(expertReviewQueryWrapper);
            //获取所有标准列表
            List<ReviewStandardVO> ReviewStandards=reviewStandardService.getListByReviewSchemeId(honorApplyBookExpertReviewResultVO.getReviewSchemeId());
            //判断是否已经分配了专家
            if(ObjectUtils.isNotEmpty(expertReviewVoList)){
                //获取专家列表
                List<AllExpertReviewVO> allExpertReviewVoList=expertReviewVoList.stream().map(expertReviewMapping::vo2AllVo).collect(Collectors.toList());
                //获取所有方案标准ID
                List<String> expertReviewIds=allExpertReviewVoList.stream().map(AllExpertReviewVO::getId).collect(Collectors.toList());
                //获取评审方案下所有专家的所有评审结果
                LambdaQueryWrapper<ReviewResultEntity> reviewResultQueryWrapper = new LambdaQueryWrapper();
                reviewResultQueryWrapper.in(ReviewResultEntity::getExpertReviewId,expertReviewIds);
                List<ReviewResultVO> reviewResultVOS= reviewResultService.getListByQueryWrapper(reviewResultQueryWrapper);
                if(ObjectUtils.isNotEmpty(allExpertReviewVoList)){
                    //遍历专家信息，设置专家审核结果
                    for (AllExpertReviewVO ae:allExpertReviewVoList) {
                        if(ae.getReviewStatus()!=null&&ae.getReviewStatus().equals("submit")){//该专家提交了审核
                            ae.setReviewResultVOs(reviewResultVOS.stream().filter(t->t.getExpertReviewId().equals(ae.getId())).collect(Collectors.toList()));
                        }
                    }
                }
                honorApplyBookExpertReviewResultVO.setAllExpertReviewVOS(allExpertReviewVoList);

            }
            honorApplyBookExpertReviewResultVO.setReviewStandardVOS(ReviewStandards);
        }
        return  honorApplyBookExpertReviewResultVO;
    }
    /**
     * 专家获取自己的评审意见
     * @param id 成果id
     * @param expertId
     * @return
     */
    @Override
    public HonorApplyBookExpertReviewResultVO honorApplyBookExpertReviewDetailByIdAndExpertId(String id,String expertId,String expertSysId){
        //获取获奖评审-查看成果列表-意见汇总-意见详情返回基本信息
        HonorApplyBookExpertReviewResultVO honorApplyBookExpertReviewResultVO=honorApplyBookMapper.honorApplyBookExpertReviewDetailById(id);
        if(ObjectUtils.isNotEmpty(honorApplyBookExpertReviewResultVO)){
            //获取该成果下所有分配的专家信息
            String reviewerId=expertReviewService.getReviewerIdByExpertId(expertId);
            LambdaQueryWrapper<ExpertReviewEntity> expertReviewQueryWrapper = new LambdaQueryWrapper();
            expertReviewQueryWrapper.eq(ExpertReviewEntity::getReviewObjectId,honorApplyBookExpertReviewResultVO.getId());
            expertReviewQueryWrapper.eq(ExpertReviewEntity::getReviewerId,reviewerId);
            List<ExpertReviewVO> expertReviewVoList = expertReviewService.selectByLambdaQueryWrapper(expertReviewQueryWrapper);
            //获取所有标准列表
            List<ReviewStandardVO> ReviewStandards=reviewStandardService.getListByReviewSchemeId(honorApplyBookExpertReviewResultVO.getReviewSchemeId());
            //判断是否已经分配了专家
            if(ObjectUtils.isNotEmpty(expertReviewVoList)){
                //获取专家列表
                List<AllExpertReviewVO> allExpertReviewVoList=expertReviewVoList.stream().map(expertReviewMapping::vo2AllVo).collect(Collectors.toList());
                //获取所有专家评审Ids
                List<String> expertReviewIds=allExpertReviewVoList.stream().map(AllExpertReviewVO::getId).collect(Collectors.toList());
                //获取评审方案下所有专家的所有评审结果
                LambdaQueryWrapper<ReviewResultEntity> reviewResultQueryWrapper = new LambdaQueryWrapper();
                reviewResultQueryWrapper.eq(ReviewResultEntity::getCreateUserId,expertSysId);
                reviewResultQueryWrapper.in(ReviewResultEntity::getExpertReviewId,expertReviewIds);
                List<ReviewResultVO> reviewResultVOS= reviewResultService.getListByQueryWrapper(reviewResultQueryWrapper);
                if(ObjectUtils.isNotEmpty(allExpertReviewVoList)){
                    //遍历专家信息，设置专家审核结果
                    for (AllExpertReviewVO ae:allExpertReviewVoList) {
                        ae.setReviewResultVOs(reviewResultVOS);
                    }
                }
                honorApplyBookExpertReviewResultVO.setAllExpertReviewVOS(allExpertReviewVoList);
            }
            honorApplyBookExpertReviewResultVO.setReviewStandardVOS(ReviewStandards);
        }
        return  honorApplyBookExpertReviewResultVO;
    }

    @Override
    public  boolean updateHonorApplyBookCheckStatus(String id,String status){
        HonorApplyBookEntity entity = new HonorApplyBookEntity();
        entity.setId(id);
        entity.setCheckstatus(status);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        entity.setCheckdate(new Date());
        entity.setChecker(SecurityUtils.getUserId().toString());
        return this.updateById(entity);
    }
    @Override
    public  boolean updateHonorApplyBookHonorState(HonorApplyBookDTO dto){
        HonorApplyBookEntity entity = new HonorApplyBookEntity();
        entity.setId(dto.getId());
        entity.setHonorState(dto.getHonorState());
        return this.updateById(entity);
    }

    @Override
    /**
     * 成果评审-专家角色获取自己评审的成果列表
     * @param expertId
     * @return
     */
    public List<HonorApplyBookByExpertVO> honorApplyBookListByExpert(Integer reviewStatus, String expertId){
        return honorApplyBookMapper.honorApplyBookListByExpert(reviewStatus,expertId);
    }
    /**
     * 管理员成果意见汇总评审
     */
    @Transactional // 开启事务
    @Override
    public boolean approveHonor(HonorApplyBookDTO dto){
        // 根据申请书籍ID获取所有相关的荣誉申请书籍成员实体列表
        HonorApplyBookEntity entity = this.getById(dto.getId());
        entity.setReviewResult(dto.getReviewResult());

        if(dto.getReviewResult().equals("pass")){
            entity.setHonorState("3");
            //入库成果库
            List<HonorApplyBookMemberEntity> honorApplyBookMemberEntities=honorApplyBookMemberMapper.honorApplyBookMemberByApplyBookId(dto.getId());
            // 将成果申请材料成员实体列表转换为成果作者实体列表（使用对象映射转换）
            List<HonorAuthorEntity> honorAuthorEntities=honorApplyBookMemberEntities.stream().map(honorAuthorMapping::honorApplyBookMemberEntity2Entity2HonorAuthorEntity).collect(Collectors.toList());
            // 遍历成果作者实体列表，逐个插入到数据库
            for (HonorAuthorEntity en:honorAuthorEntities){
                en.setId(UUID.randomUUID().toString().replace("-",""));
                en.setHonorId(entity.getId());
                honorAuthorMapper.insert(en);
            }
            // 将成果申请材料实体转换为成果实体（使用对象映射转换）
            HonorEntity honor= honorMapping.honorApplyBook2HonorEntity(entity);
            //设置成果名称
            honor.setName(entity.getHonorName());
            honor.setId(entity.getId());
            honor.setCheckstatus("-2");//待完善
            // 将荣誉实体插入到荣誉表中
            honorMapper.insert(honor);
        }

        return this.updateById(entity);
    }
    @Transactional // 开启事务
    @Override
    public boolean revokeHonor(HonorApplyBookDTO dto){
        // 根据申请书籍ID获取所有相关的荣誉申请书籍成员实体列表
        HonorApplyBookEntity entity = this.getById(dto.getId());
        entity.setReviewResult(dto.getReviewResult());
        if(dto.getReviewResult().equals("noPass")){
            entity.setHonorState("2");
            //入库成果库
            List<HonorApplyBookMemberEntity> honorApplyBookMemberEntities=honorApplyBookMemberMapper.honorApplyBookMemberByApplyBookId(dto.getId());
            // 将成果申请材料成员实体列表转换为成果作者实体列表（使用对象映射转换）
            List<HonorAuthorEntity> honorAuthorEntities=honorApplyBookMemberEntities.stream().map(honorAuthorMapping::honorApplyBookMemberEntity2Entity2HonorAuthorEntity).collect(Collectors.toList());
            // 删除原来的作者表
            honorAuthorMapper.deleteAuthorListByHonorId(entity.getId());
            // 将成果申请材料实体转换为成果实体（使用对象映射转换）
            HonorEntity honor= new HonorEntity();
            honor.setId(dto.getId());
            // 将荣誉实体插入到荣誉表中
            honorMapper.deleteById(honor);
        }

        return this.updateById(entity);
    }

    @Override
    public void updateBusinessStatus(String tableName, String businessId, String checkStatus, String sysUserId) {

    }
    @Override
    public boolean updateHonorState(HonorApplyBookDTO dto){
        HonorApplyBookEntity entity=new HonorApplyBookEntity();
        if(dto.getHonorState()!=null&&(dto.getHonorState().equals("1")||dto.getHonorState().equals("2"))){
            //生成honorApplyBook成绩
            LambdaQueryWrapper<ExpertReviewEntity> expertReviewQueryWrapper = new LambdaQueryWrapper();
            expertReviewQueryWrapper.eq(ExpertReviewEntity::getReviewObjectId,dto.getId());
            List<ExpertReviewVO> expertReviewVoList = expertReviewService.selectByLambdaQueryWrapper(expertReviewQueryWrapper);
            if(ObjectUtils.isNotEmpty(expertReviewVoList)){
                double reviewMark=0;
                int count=0;
                //遍历专家评审结果，设置专家审核结果
                for (ExpertReviewVO er:expertReviewVoList) {
                    if(er.getReviewStatus().equals("submit")){
                        reviewMark+=er.getReviewMark();
                        count++;
                    }
                }
                if(count>0){
                    double reviewMark2=reviewMark/count;
                    entity.setReviewMark(reviewMark2);//计算平均分
                }
            }
        }
        entity.setHonorState(dto.getHonorState());
        entity.setId(dto.getId());
        if(dto.getHonorState().equals("1")){
            entity.setReviewResult("pass");//通过
        }else if(dto.getHonorState().equals("2")){
            entity.setReviewResult("noPass");//不通过
        }else if(dto.getHonorState().equals("3")){
            entity.setReviewResult("award");//获奖
        }
        if(StringUtils.isNotEmpty(dto.getReviewInfo())){
            entity.setReviewInfo(dto.getReviewInfo());
        }
        return this.updateById(entity);
    }
}
